package com.ruicar.afs.cloud.afscase.channel.task;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelRiskInfo;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelRiskInfoService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.ruicar.afs.cloud.afscase.channel.utils.Common.QUALITY_LEVEL_FIVE;

/**
 * @author mingzhi.li
 */
@Slf4j
@Component
@RestController
@AllArgsConstructor
public class QualityLevelTask {
    /**
     * 风控信息表
     */
    private ChannelRiskInfoService service;

    /**
     * 每天上午10点、下午14点、下午16点执行
     */
    @Scheduled(cron = "0 0 10,14,16 * * ?")
    public void start() {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        //获取当前日期时间
        Long dayTime = calendar.getTime().getTime();
        //Step1：查询额度信息表数据并更新数据库
        List<ChannelRiskInfo> list = service.list(Wrappers.<ChannelRiskInfo>query().lambda());
        List<ChannelRiskInfo> infoList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                ChannelRiskInfo info = list.get(i);
                if(StrUtil.isBlank(info.getQualityEndDate())){
                    continue;
                }
                Long endTime = new Date(info.getQualityEndDate()).getTime();
                //判断如果当前日期大于优质等级有效期，则更新优质等级为无
                if (dayTime >= endTime) {
                    info.setQualityGrade(QUALITY_LEVEL_FIVE);
                    service.updateById(info);
                    infoList.add(info);
                }
            }

            //Step2: 调用渠道服务更新优质等级信息
            service.synchronousQualityLevelToChannel(infoList);
        }
    }
}
